package com.zhihuitong.meeting.meeting.list;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huawei.cloudlink.openapi.api.CLMCompleteHandler;
import com.huawei.cloudlink.openapi.api.CLMResult;
import com.huawei.cloudlink.openapi.api.CloudLinkSDK;
import com.huawei.cloudlink.openapi.api.OpenApiConst;
import com.zhihuitong.meeting.R;
import com.zhihuitong.meeting.base.BaseListFragment;
import com.zhihuitong.meeting.dao.LocalMeetingBean;
import com.zhihuitong.meeting.dao.SQLiteUtils;
import com.zhihuitong.meeting.global.HuaWeiUserProvider;
import com.zhihuitong.meeting.global.MyApplication;
import com.zhihuitong.meeting.utils.ShareUtils;
import com.zhihuitong.meeting.utils.ToastUtils;
import com.zhihuitong.meeting.view.CustomDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 作者： guoyuan
 * 时间 2020/2/24.
 * 文件描述：
 * 版本号：V 1.0
 **/
public class MeetingListFragment extends BaseListFragment<LocalMeetingBean, MeetingListPresenter> implements MeetingListContract.IMeetingListView {

    public static MeetingListFragment getInstance() {
        MeetingListFragment fragment = new MeetingListFragment();
        return fragment;
    }

    protected CustomDialog mDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        mDialog = new CustomDialog(getActivity());
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected MeetingListPresenter createPresenter() {
        return new MeetingListPresenter(this);
    }

    /**
     * 创建适配器
     *
     * @return
     */
    @Override
    protected BaseQuickAdapter<LocalMeetingBean, BaseViewHolder> createBaseQuickAdapter() {
        return new MeetingListAdapter(null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LocalMeetingBean bean) {
        refresh();
    }

    /**
     * 刷新的方法
     */
    @Override
    protected void refresh() {
        mPresenter.loadData(false);
    }

    @Override
    protected void loadMoreData(List<LocalMeetingBean> data) {
        mPresenter.loadData(true);
    }

    @Override
    public void onNewData(List<LocalMeetingBean> list) {
        mStateView.showContent();
        setNewData(list);
    }

    @Override
    public void onMoreData(List<LocalMeetingBean> list) {
        addData(list);
    }

    @Override
    public void onDataEmpty() {
        mStateView.showContent();
        setNewData(null);
    }

    @Override
    public void onNewDataFail(String msg) {
        mStateView.showRetry();
        ToastUtils.showToast(msg);
    }

    @Override
    public void noMore() {
        loadDataEnd();
    }

    @Override
    public void loadMoreError(String msg) {
        loadDataFail();
        ToastUtils.showToast(msg);
    }

    @Override
    protected void onItemChildClick(View view, int position, LocalMeetingBean entity) {
        switch (view.getId()) {
            case R.id.btn_joinMeeting:
                showLoading();
                // getHuaWeiAccount(entity);
                joinMeeting(entity);
                break;
            case R.id.btn_shareMeeting:
                try {
                    ShareUtils.showShare(getContext(), entity);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 加入会议
     *
     * @param entity
     */
    private void joinMeeting(LocalMeetingBean entity) {

        //使用来宾密码入会
        CloudLinkSDK.getOpenApi().clmJoinMeetingById(entity.getConferenceID(), entity.getGeneralPwd(), MyApplication.getLocalUserName(), new CLMCompleteHandler() {
            @Override
            public void onCompleted(CLMResult result) {
                hidLoading();
                if (result.getCmd().equals(OpenApiConst.OPEN_EVENT_JOIN_MEETING_BY_ID)) {
                    Log.i("huawei", "join meeting result" + result.getMessage());
                    if (result.getCode() != 0) {
                        ToastUtils.showToast(result.getMessage());
                        Log.e("huawei", "join meeting fail" + result.getMessage());
                    }
                }
            }
        });
    }

    /**
     * 获取华为云账号
     *
     * @param entity
     */
    private void getHuaWeiAccount(final LocalMeetingBean entity) {
        //先获取华为云账号
        HuaWeiUserProvider.getUser(MyApplication.getLocalAccount(), MyApplication.getLocalPwd(), new HuaWeiUserProvider.onHuaWeiUserListener() {
            @Override
            public void onHuaWeiUserSuccess(String userId, String pwd) {
                //华为账号登陆
                HuaWeiUserProvider.huaWeiLogin(userId, pwd, new CLMCompleteHandler() {
                    @Override
                    public void onCompleted(CLMResult result) {
                        if (result.getCode() == 0) {
                            ToastUtils.showToast("账号登录成功");
                            //加入会议
                            joinMeeting(entity);
                        } else {
                            hidLoading();
                            Log.e("huawei", "login fail" + result.getMessage());
                            ToastUtils.showToast("账号登录失败" + "\nlogin fail" + result.getMessage());
                        }
                    }
                });

            }

            @Override
            public void onHuaWeiUserFail(String msg) {
                ToastUtils.showToast(msg);
                hidLoading();
            }
        });
    }

    protected void showLoading() {
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }
    }


    protected void hidLoading() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();

        }
    }

    @Override
    protected void onItemLongClick(View view, final int position, final LocalMeetingBean entity) {
        new AlertDialog.Builder(getContext())
                .setTitle("确认删除这条会议数据?")
                .setMessage("会议主题:" + entity.getSubject() + "\n" + "创建人:" + entity.getScheduserName())
                .setCancelable(false)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        boolean b = SQLiteUtils.deletMeetById(entity.getId());
                        if (b) {
                            ToastUtils.showToast("删除成功");
                            mBaseQuickAdapter.remove(position);
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }
}
